// pages/city/city.js
const {city} = require("../../models/city")
Page({
  data: {
    data:{},
    indexList:[],
    position:'',
    visited:[],
    search:"",
    arr:[]
  },
  onLoad: async function (options) {
    // 获取当前定位
    var position = wx.getStorageSync('position')
    // 获取访问过的城市
    let visited = wx.getStorageSync('visited')
    if(!visited){
      wx.setStorageSync('visited', [])
    }

    // 请求数据
    let res = await city()
    var data = res.data.data;
    // 获取city的key
    var indexList = Object.keys(data.cities);
    this.setData({
      data,
      indexList,
      position,
      visited
    })
  },

  goBack(event){
    
    wx.setStorageSync('nowCity',event.currentTarget.dataset.name);
    var visited = wx.getStorageSync('visited');
    if(!visited.includes(event.currentTarget.dataset.name.trim())){
      visited.unshift(event.currentTarget.dataset.name)
      visited = visited.slice(0,3)
      wx.setStorageSync('visited',visited);
    }
    this.setData({
      visited
    })
    wx.navigateBack({
      delta: 1
    })
  },

  // 监听输入框
  onChange(event){
    var arr = [];
    this.setData({
      search:event.detail.trim()
    })
    
    for(var res in this.data.data.cities){
      this.data.data.cities[res].forEach(item=>{
        if(item.name.includes(this.data.search) || item.spell.includes(this.data.search)){
          arr.push(item)
        }
      })
    }
    this.setData({
      arr
    })
    
  } 
})